package com.cu.jiekong.controller;

import com.cu.jiekong.constants.ResultStatus;
import com.cu.jiekong.frame.exception.BizException;
import com.cu.jiekong.frame.model.Ret;
import com.cu.jiekong.model.User;
import com.cu.jiekong.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("user")
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("login")
    public Ret login(HttpServletRequest request, User user) {
        try {
            return userService.login(request, user);
        } catch (Exception e) {
            logger.error("login error:", e);
            return new Ret(ResultStatus.RESULT_999999.getCode(), ResultStatus.RESULT_999999.getMsg());
        }
    }

    /**
     * 登出
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("loginOut")
    public Ret loginOut(Integer userId, HttpServletRequest request) {
        try {
            return userService.loginOut(userId, request);
        } catch (Exception e) {
            logger.error("loginOut error:", e);
            return new Ret(ResultStatus.RESULT_999999.getCode(), ResultStatus.RESULT_999999.getMsg());
        }
    }

    /**
     * 根据用户id 获取用户信息
     *
     * @param userId
     * @param sign
     * @return
     */
    @ResponseBody
    @RequestMapping("getUserById")
    public Ret getUserByUserId(String userId, String sign) {
        try {
            if (StringUtils.isBlank(userId) || StringUtils.isBlank(sign)) {
                return new Ret(ResultStatus.RESULT_100001.getCode(), ResultStatus.RESULT_100001.getMsg());
            }
            return new Ret(ResultStatus.RESULT_000000.getCode(), ResultStatus.RESULT_000000.getMsg(), userService.getUserByUserId(userId, sign));
        } catch (BizException e) {
            return new Ret(e.getCode(), e.getMsg());
        } catch (Exception e) {
            logger.error("getUserById error:", e);
            return new Ret(ResultStatus.RESULT_999999.getCode(), ResultStatus.RESULT_999999.getMsg());
        }
    }
}
